﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TPLOAWebService.Models;

namespace TPLOAWebService.Controllers
{
    public class LOAsController : ApiController
    {
        static readonly ILOARepository repository = new LOARepository();

        public IEnumerable<LOA> GetAllLOAs()
        {
            return repository.GetAll();
        }

        public LOA GetLOA(int id)
        {
            LOA item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }

        public IEnumerable<LOA> GetLOAsByAdminNo(string an)
        {
            return repository.GetAll().Where(
                p => string.Equals(p.StudentAdminNo, an, StringComparison.OrdinalIgnoreCase));
        }

        public IEnumerable<LOA> GetLOAsByCourseCode(string cc)
        {
            return repository.GetLOAByCourseCode(cc);
        }

        public HttpResponseMessage PostLOA(LOA item)
        {
            item = repository.Add(item);
            var response = Request.CreateResponse<LOA>(HttpStatusCode.Created, item);

            string uri = Url.Link("DefaultApi", new { id = item.LOAID });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void PutLOA(int id, LOA loa)
        {
            loa.LOAID = id;
            if (!repository.Update(loa))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public HttpResponseMessage DeleteLOA(int id)
        {
            repository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}
